package com.zc.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.zc.oss.service.OssService;
import com.zc.oss.utils.ConstantProperties;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
	@Override
	public String uploadAvatar(MultipartFile file) {
		String endpoint = ConstantProperties.END_POINT;
		// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
		String accessKeyId = ConstantProperties.ACCESS_KEY_ID;
		String accessKeySecret = ConstantProperties.ACCESS_KEY_SECRET;
		// 填写Bucket名称，例如examplebucket。
		String bucketName = ConstantProperties.BUCKET_NAME;
		// 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		String date = new DateTime().toString("yyyy/MM/dd");
		String fileName = date + "/" + uuid + file.getOriginalFilename();



		// 创建OSSClient实例。
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

		try {
			InputStream inputStream = file.getInputStream();
			// 创建PutObject请求。
			ossClient.putObject(bucketName, fileName, inputStream);
		} catch (Exception e) {
			return null;
		} finally {
			if (ossClient != null) {
				ossClient.shutdown();
			}
		}
		String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
		return url;
	}
}
